package cn.afactory.tygz;

import android.app.Activity;
import android.app.Application;
import android.content.Context;

import java.util.ArrayList;

/**
 * Created with Android Studio.
 * Title:BaseApplication
 * Description:
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:Alice
 * Date:15/8/18
 * Time:下午2:47
 * Version 1.0
 */
public class BaseApplication extends Application {
    protected static ArrayList<Activity> activityList = new ArrayList<Activity>();

    protected static Context mContext;

    @Override
    public void onCreate() {
        mContext = this;

        super.onCreate();
    }

    public void finishActivity(Activity item) {
        if (item == null)
            return;
        if (activityList.contains(item)) {
            if (item.isFinishing()) {
                activityList.remove(item);
            } else {
                item.finish();
                activityList.remove(item);
            }
        } else {
            item.finish();
        }
    }

    public void addActivity(Activity item) {
        if (item == null)
            return;

        if (!activityList.contains(item)) {
            activityList.add(0, item);
        } else {
            upActivityItem(item);
        }
    }

    public void removeActivity(Activity item) {
        if (item == null)
            return;
        if (activityList.contains(item)) {
            activityList.remove(item);
        }
    }

    public void removeActivityClass(Class<?> activityClass) {
        if (activityClass == null)
            return;
        for (Activity activity : activityList) {
            if (activity.getClass().equals(activityClass)) {
                removeActivity(activity);
            }
        }
    }

    public boolean isActivityOpened(Class<?> activityClass) {
        for (Activity activity : activityList) {
            if (activity.getClass().equals(activityClass)) {
                return true;
            }
        }
        return false;
    }

    public void exitAllActivity() {
        Activity activity;
        for (int i = (activityList.size() - 1); i >= 0; i--) {
            activity = (Activity) activityList.get(i);
            if (activity != null) {
                activity.finish();
            }
        }
        activityList.clear();
    }

    private void upActivityItem(Activity item) {
        if (item == null)
            return;
        if (!activityList.contains(item))
            return;
        activityList.remove(item);
        activityList.add(0, item);
    }

    public static Context getAppContext() {
        return mContext;
    }
}
